﻿using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using PolePosition.v3.EntityLibrary;

namespace PolePosition.v3.Desktop.Editors.Controls
{
    public partial class DistributionPole : DialogEditBase
    {
        public DistributionPole()
        {
            InitializeComponent();
       
            BindCombos();
        }

        private ProjectCommon2.Generics.EntityCollection<VendorDistributionTopsXPoleEntity> m_VisitTops;
        private ProjectCommon2.Generics.EntityCollection<VendorDistributionPhasesXPoleEntity> m_VisitPhases;

        public Common.Enumerations.DataTypes DataType { get; private set; }

        private void BindCombos()
        {
            if (Program.LookupTableData != null)
            {
                ComboOptions.PoleSpecies(comboBoxSpecies);
                ComboOptions.PoleDistributionClass(comboBoxClass);
                ComboOptions.PoleDistributionLengths(comboBoxLength);
                ComboOptions.PoleTreatment(comboBoxTreatment);
                ComboOptions.DistributionLookUp(comboBoxKv, VendorDistributionLookupsType.Kv);
                ComboOptions.DistributionLookUp(comboBoxACSR, VendorDistributionLookupsType.ACSR);
                ComboOptions.DistributionLookUp(comboBoxConductorType, VendorDistributionLookupsType.ConductorType);
           
                listSelectorTopType.DisplayMember = DistributionsTopTypeEnumerations.Columns.Name.ToString();
                listSelectorTopType.ValueMember = DistributionsTopTypeEnumerations.Columns.Distributions_TopTypeId.ToString();
                if (EditAllowed)
                    listSelectorTopType.DataSource = Program.LookupTableData.DistributionsTopTypes;
                else
                    listSelectorTopType.Clear();

                listSelectorPhase.DisplayMember = DistributionPhaseEnumerations.Columns.Name.ToString();
                listSelectorPhase.ValueMember = DistributionPhaseEnumerations.Columns.PhaseId.ToString();
                if (EditAllowed)
                    listSelectorPhase.DataSource = Program.LookupTableData.DistributionPhases;
                else
                    listSelectorPhase.Clear();

            }

            if (Program.LoginResult != null && Program.LoginResult.Polygons != null)
                ComboOptions.Maps(comboBoxMap);
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public object Data
        {
            get
            {
                return bindingSourcePole.DataSource;
            }
            set
            {
                bindingSourcePole.SuspendBinding();
                SetupDatabindings(value);
                bindingSourcePole.DataSource = value;
                bindingSourcePole.ResumeBinding();
            }
        }

        [DefaultValue(false)]
        private bool m_EditAllowed;
        public bool EditAllowed 
        {
            get 
            {
                return m_EditAllowed;
            }
            set
            {
                m_EditAllowed = value;

                textBoxSection.ReadOnly = !m_EditAllowed;
                textBoxLongitude.ReadOnly = !m_EditAllowed;
                textBoxLatitude.ReadOnly = !m_EditAllowed;
                textBoxYear.ReadOnly = !m_EditAllowed;
                textBoxLVisit.ReadOnly = !m_EditAllowed;
                textBoxLVisitBy.ReadOnly = !m_EditAllowed;

                comboBoxMap.Enabled = !m_EditAllowed; 
                comboBoxClass.Enabled = m_EditAllowed;
                comboBoxMap.Enabled = m_EditAllowed;
                comboBoxTreatment.Enabled = m_EditAllowed;
                comboBoxSpecies.Enabled = m_EditAllowed;
                comboBoxKv.Enabled = m_EditAllowed;
                comboBoxACSR.Enabled = m_EditAllowed;
                comboBoxConductorType.Enabled = m_EditAllowed;

                listSelectorPhase.ReadOnly = !m_EditAllowed;
                listSelectorTopType.ReadOnly = !m_EditAllowed;
            }
        }

        private void SetupDatabindings(object data)
        {
            if (data.GetType() == typeof(VendorDistributionPoleEntity))
            {
                DataType = Common.Enumerations.DataTypes.ProjectsDistributionInspection;

                bindingSourcePole.DataSource = typeof(VendorDistributionPoleEntity);
                textBoxSection.DataBindings.Add(new Binding("Text", bindingSourcePole, "SectionFk", true, DataSourceUpdateMode.OnPropertyChanged));
                comboBoxMap.DataBindings.Add(new Binding("SelectedValue", bindingSourcePole, "MapFk", true, DataSourceUpdateMode.OnPropertyChanged));
                textBoxLongitude.DataBindings.Add(new Binding("Text", bindingSourcePole, "Longitude", true, DataSourceUpdateMode.OnPropertyChanged));
                textBoxLatitude.DataBindings.Add(new Binding("Text", bindingSourcePole, "Latitude", true, DataSourceUpdateMode.OnPropertyChanged));
                textBoxYear.DataBindings.Add(new Binding("Text", bindingSourcePole, "Year", true, DataSourceUpdateMode.OnPropertyChanged));
                comboBoxTreatment.DataBindings.Add(new Binding("SelectedValue", bindingSourcePole, "TreatmentFk", true, DataSourceUpdateMode.OnPropertyChanged));
                comboBoxClass.DataBindings.Add(new Binding("SelectedValue", bindingSourcePole, "ClassFK", true, DataSourceUpdateMode.OnPropertyChanged));
                comboBoxLength.DataBindings.Add(new Binding("SelectedValue", bindingSourcePole, "LengthFk", true, DataSourceUpdateMode.OnPropertyChanged));
                comboBoxSpecies.DataBindings.Add(new Binding("SelectedValue", bindingSourcePole, "SpecieFk", true, DataSourceUpdateMode.OnPropertyChanged));
                
                comboBoxKv.DataBindings.Add(new Binding("SelectedValue", bindingSourcePole, "Kv", true, DataSourceUpdateMode.OnPropertyChanged));
                comboBoxACSR.DataBindings.Add(new Binding("SelectedValue", bindingSourcePole, "ACSR", true, DataSourceUpdateMode.OnPropertyChanged));
                comboBoxConductorType.DataBindings.Add(new Binding("SelectedValue", bindingSourcePole, "ConductorType", true, DataSourceUpdateMode.OnPropertyChanged));

                textBoxLVisit.DataBindings.Add(new Binding("Text", bindingSourcePole, "LVisit", true, DataSourceUpdateMode.OnPropertyChanged));
                textBoxLVisitBy.DataBindings.Add(new Binding("Text", bindingSourcePole, "InspBy", true, DataSourceUpdateMode.OnPropertyChanged));
                textBoxNumber.DataBindings.Add(new Binding("Text", bindingSourcePole, "Number", true, DataSourceUpdateMode.OnPropertyChanged));
                textBoxCircuit.DataBindings.Add(new Binding("Text", bindingSourcePole, "Circuit", true, DataSourceUpdateMode.OnPropertyChanged));

                LoadDataAsynch((data as PolePosition.v3.EntityLibrary.VendorDistributionPoleEntity).Vendor_Distribution_Poles_PoleId.Value);
            }
        }

        private void LoadDataAsynch(int poleId)
        {
            listSelectorPhase.LoadingVisible = true;
            listSelectorTopType.LoadingVisible = true;
            backgroundWorkerTops.RunWorkerAsync(poleId);
            backgroundWorkerPhases.RunWorkerAsync(poleId);
        }

        private void backgroundWorkerTops_DoWork(object sender, DoWorkEventArgs e)
        {
            if (DataType == Common.Enumerations.DataTypes.ProjectsDistributionInspection)
                m_VisitTops = ServiceProxy.UtilityService.GetDistributionInspectionProjectTopsForPole((int)e.Argument);

            if (backgroundWorkerTops.CancellationPending)
                e.Cancel = true;
        }

        private void backgroundWorkerTops_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;

            listSelectorTopType.LoadingVisible = false;

            if (e.Error != null)
            {
                DevComponents.DotNetBar.MessageBoxEx.Show("A Data Retrieval Error has occurred attempting to load the top types. Please close editor and try again.", "Data Retrieval Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                listSelectorTopType.Enabled = false;
                return;
            }

            if (DataType == Common.Enumerations.DataTypes.ProjectsDistributionInspection)
            {
                if (m_VisitTops != null)
                {
                    if (EditAllowed)
                    {
                        var _TopValues = from tops in m_VisitTops
                                         select tops.Vendor_Distribution_TopFk.Value;
                        listSelectorTopType.SetSelectedValues<int>(_TopValues.ToList<int>());
                    }
                    else
                    {
                        if (m_VisitTops.Count() > 0)
                        {

                            //this will only show selected items
                            var _TopValues = from tops in m_VisitTops
                                             join lookupdata in Program.LookupTableData.DistributionsTopTypes
                                             on tops.Vendor_Distribution_TopFk equals lookupdata.Distributions_TopTypeId
                                             select lookupdata;

                            listSelectorTopType.ReadOnlyNoneSelectedVisible = false;
                            listSelectorTopType.DataSource = _TopValues.ToList();
                        }
                        else
                        {
                            listSelectorTopType.ReadOnlyNoneSelectedVisible = true;
                        }
                    }
                }

                listSelectorTopType.Enabled = true;
            }
        }

        private void backgroundWorkerPhases_DoWork(object sender, DoWorkEventArgs e)
        {
            if (DataType == Common.Enumerations.DataTypes.ProjectsDistributionInspection)
                m_VisitPhases = ServiceProxy.UtilityService.GetDistributionInspectionProjectPhasesForPole((int)e.Argument);

            if (backgroundWorkerPhases.CancellationPending)
                e.Cancel = true;
        }

        private void backgroundWorkerPhases_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;

            listSelectorPhase.LoadingVisible = false;

            if (e.Error != null)
            {
                DevComponents.DotNetBar.MessageBoxEx.Show("A Data Retrieval Error has occurred attempting to load the phases. Please close editor and try again.", "Data Retrieval Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                listSelectorPhase.Enabled = false;
                return;
            }

            if (DataType == Common.Enumerations.DataTypes.ProjectsDistributionInspection)
            {
                if (m_VisitPhases != null)
                {
                    if (EditAllowed)
                    {
                        var _PhaseValues = from phase in m_VisitPhases
                                           select phase.Vendor_Distribution_PhaseFk.Value;
                        listSelectorPhase.SetSelectedValues<int>(_PhaseValues.ToList<int>());
                    }
                    else
                    {
                        if (m_VisitTops.Count() > 0)
                        {
                            //this will only show selected items
                            var _PhaseValues = from phase in m_VisitPhases
                                               join lookupdata in Program.LookupTableData.DistributionPhases
                                               on phase.Vendor_Distribution_PhaseFk equals lookupdata.PhaseId
                                               select lookupdata;

                            listSelectorPhase.ReadOnlyNoneSelectedVisible = false;
                            listSelectorPhase.DataSource = _PhaseValues.ToList();
                        }
                        else
                        {
                            listSelectorPhase.ReadOnlyNoneSelectedVisible = true;
                        }
                    }
                }

                listSelectorPhase.Enabled = true;
            }
        }
    }
}
